package core

import (
	"biliClient/global"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/tidwall/gjson"
)

var Token string

func init() {
	ServiceLogin()
}

// ServiceLogin 登录
func ServiceLogin() {
	data := map[string]string{"username": "admin", "password": "fjiabinc"}
	b, _ := json.Marshal(data)
	URL := fmt.Sprintf("%v/user/login", global.Config.Service.Host)
	resp, _ := http.Post(URL, "", strings.NewReader(string(b)))
	body, _ := ioutil.ReadAll(resp.Body)
	Token = gjson.Get(string(body), "data.token").String()
	_ = resp.Body.Close()
}

// CheckDeviceID 获取设备ID
func CheckDeviceID(mac string) string {
	URL := fmt.Sprintf("%v/device", global.Config.Service.Host)
	req, err := http.NewRequest("GET", URL, nil)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	param := req.URL.Query()
	param.Set("mac", mac)
	req.URL.RawQuery = param.Encode()
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)
	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	s := gjson.Get(string(bytes), "data.id").String()
	return s
}
